package middleware

import (
	"ReaderInOutLog/logger"
	"fmt"
	"math"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// Logger 返回一个日志中间件以及配置好的日志实例
func Logger() gin.HandlerFunc {

	// 配置日志
	logger, err := logger.ConfigureLogger()
	if err != nil {
		logger.Error(err)
		return nil
	}

	return func(c *gin.Context) {
		startTime := time.Now()
		c.Next()
		stopTime := time.Since(startTime)
		spendTime := fmt.Sprintf("%d ms", int(math.Ceil(float64(stopTime.Nanoseconds())/1000000.0)))
		hostName, err := os.Hostname()
		if err != nil {
			hostName = "unknown"
		}
		statusCode := c.Writer.Status()
		clientIp := c.ClientIP()
		method := c.Request.Method
		userAgent := c.Request.UserAgent()
		dataSize := c.Writer.Size()
		if dataSize < 0 {
			dataSize = 0
		}
		path := c.Request.RequestURI
		entry := logger.WithFields(logrus.Fields{
			"hostname": hostName,
			"status":   statusCode,
			"latency":  spendTime, // 毫秒
			"ip":       clientIp,
			"method":   method,
			"path":     path,
			"ua":       userAgent,
			"size":     dataSize,
		})
		if len(c.Errors) > 0 {
			entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
		}
		if statusCode >= 500 {
			entry.Error()
		} else if statusCode >= 400 {
			entry.Warn()
		} else {
			entry.Info()
		}
	}
}
